// sessionStorage.setItem("token","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMSIsImlhdCI6MTU0MzU1OTMwNCwiZXhwIjoxNTQ0MTY0MTA0fQ.vaUbUWu4pCTeIWVxfPvh1cVy1JUJvGaLtiPlST4tzoM16UBps4uXgdkBwC6svvQPCpucqceb9p295VJf8sr_qA")

var baseUrl = "https://www.yunlianmen.com/ylm/app/";
var imgBaseurl = "https://www.yunlianmen.com/ylmFile/";
var token = sessionStorage.getItem("token");
var phone_rexg = /^1\d{10}$/;

if(!sessionStorage.getItem("token")){
    goWx()
}

function goWx() {
    var code = getUrlParam('code');
    var state = getUrlParam("state");
    var leadUserId = state && state != 'false' && state != 'null' && state != 'STATE'?state:false;
    if(code){
        ajax_async("/weixin/wxWebLogin",{code:code},function (data) {
            var info = data.user;
            token = data.token;
            sessionStorage.setItem("token",data.token);
            sessionStorage.setItem("userId",info.userId);
            if(!info.mobile){
                var str = '<div class="mask"style="display: block"></div><div class="bindPhone">'+
                    '<div class="title">绑定手机号</div>'+
                    '<div class="input"><span>手机号</span><input type="tel" id="bindPhone"></div>'+
                    '<div class="input"><span>验证码</span><input type="text" id="bindCode">'+
                    '<button id="btnVerify">发送验证码</button></div>'+
                    '<div class="btn_box" id="bind_btn">确认</div>'+'</div>';
                $("body").append(str);
            }else{
                sessionStorage.setItem("phone",data.mobile);
            }
            if(info.hasLead == 0 && leadUserId){
                get_ajax("/user/bindLeadUser",{leadUserId:leadUserId,token:data.token},function (data) {})
            }
        })
    }else {
        var url = encodeURI('https://www.yunlianmen.com/mobile/page/' + pageName(location.href));
        var href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb056d83ca3f89ec6&redirect_uri='+
            url+'&response_type=code&scope=snsapi_userinfo&state='+leadUserId+'#wechat_redirect';
        location.replace(href);
    }
}


var wait=60;//时间  
var t;//计时器  
function time(){
    if (wait == 0) {
        $('#btnVerify').removeAttr('disabled');
        $('#btnVerify').text("获取验证码");
        wait = 60;
        stopTime();
    }else{
        $('#btnVerify').attr('disabled','disabled');
        $('#btnVerify').text("重新发送(" + wait + "s)");
        wait--;
        t=setTimeout(function(){
            time();
        },1000)
    }
}

function stopTime(){
    clearTimeout(t);
}

$(document).on("click","#btnVerify",function () {
    var phone = $("#bindPhone").val();
    if(!phone){
        mui.toast("请输入手机号");
        return
    }
    if(!phone_rexg.test(phone)){
        mui.toast("请输入正确的手机号");
        return
    }
    get_ajax("/user/getMobileMsg",{mobile:phone,token:token},function (data) {
        mui.toast("验证码已发送");
        time();
    })
})

$(document).on("click","#bind_btn",function () {
    var yzm = $("#bindCode").val();
    var phone = $("#bindPhone").val();
    if(!phone){
        mui.toast("请输入手机号");
        return
    }
    if(!yzm){
        mui.toast("请输入验证码");
        return
    }
    get_ajax("/user/bindMobile",{mobile:phone,code:yzm,token:token},function (data) {
        mui.toast("手机号绑定成功");
        sessionStorage.setItem("phone",phone);
        $(".mask,.bindPhone").fadeOut();
    })
});


//获取路径参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r != null){
        return decodeURIComponent(r[2]);
    }
    return null;
}

//获取当前页面名称
function pageName() {
    var strUrl=location.href;
    var arrUrl=strUrl.split("/");
    var strPage=arrUrl[arrUrl.length-1];
    return strPage;
}

//返回
$("body").on("click","header .icon_back",function () {
  history.go(-1);
})

// ajax封装
function get_ajax(url,sendData,rebackFun) {
    // if(localStorage.getItem("Token")){
    //     sendData["Token"] = localStorage.getItem("Token");
    // }
    $.post(baseUrl+url,sendData,function (data) {
        if(data.code != 0){
            alert(data.msg);
            return
        }else{
            var data = data;
            rebackFun(data);
        }
    })
}

function ajax_async(url,sendData,rebackFun) {
    // if(localStorage.getItem("Token")){
    //     sendData["Token"] = localStorage.getItem("Token");
    // }
    $.ajax({
        url: baseUrl+url,
        data:sendData,
        async:false,
        type:'POST',
        success:function (data) {
            if(data.code != 0){
                alert(data.msg);
            }else{
                var data = data;
                rebackFun(data);
            }
        }
    })
}


$("body").on("click",".phone-icon",function () {
    var phone = $(this).attr("phone");
    location.href = "tel:" + phone;
})

//右下角小圆
var toMineBall = '<a class="toMine"></a>';

$("body").append(toMineBall);
$("body").append('<div class="minhome"></div>');

var toMineBallC = '<div class="toMine-c hide">'
    +'<a class="text-sty" onclick="location.href = \'index.html\'">云家故事首页</a>'
    +'<a class="text-sty" onclick="location.href = \'mine.html\'">云家故事个人中心</a>'
    +'</div>';
$("body").append(toMineBallC);

$(document).on('click','.toMine',function(){
    $('.toMine-c').toggleClass('hide');
    $('.minhome').toggleClass('mask-sty1');
})

// console.log(location.href)
get_ajax("common/getJSParam",{url:location.href},function (data) {
    wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: 'wxb056d83ca3f89ec6', // 必填，公众号的唯一标识
        timestamp: data.timestamp, // 必填，生成签名的时间戳
        nonceStr: data.nonceStr, // 必填，生成签名的随机串
        signature: data.signature,// 必填，签名，见附录1
        jsApiList: [
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ'
        ]
    });
})

var shareLink = 'https://www.yunlianmen.com/mobile/page/index.html?leadUserId='+sessionStorage.getItem("userId");
var shareTitle = "云家故事";
var shareDesc = "云家故事，你的家庭影像顾问";
var shareImg = 'https://www.yunlianmen.com/mobile/img/share.png';

wx.ready(function () {
    //分享朋友圈
    wx.onMenuShareTimeline({
        title: shareTitle,
        link: shareLink,
        imgUrl: shareImg,// 自定义图标
        trigger: function (res) {
            // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回.
            //alert('click shared');
        },
        success: function (res) {
            //alert('shared success');
            //some thing you should do
        },
        cancel: function (res) {
            //alert('shared cancle');
        },
        fail: function (res) {
            //alert(JSON.stringify(res));
        }
    });
    //分享给好友
    wx.onMenuShareAppMessage({
        title: shareTitle, // 分享标题
        desc: shareDesc, // 分享描述
        link: shareLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: shareImg, // 自定义图标
        type: 'link', // 分享类型,music、video或link，不填默认为link
        success: function () {
            // 用户确认分享后执行的回调函数
        },
        cancel: function () {
            // 用户取消分享后执行的回调函数
        }
    });
    wx.onMenuShareQQ({
        title: shareTitle, // 分享标题
        desc: shareDesc, // 分享描述
        link: shareLink, // 分享链接
        imgUrl: shareImg, // 分享图标
        success: function() {
            // 用户确认分享后执行的回调函数
        },
        cancel: function() {
            // 用户取消分享后执行的回调函数
        }
    });
    wx.error(function (res) {
        alert(res.errMsg);
    });
});






